package org.lw.server.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.lw.server.common.RespBean;
import org.lw.server.dto.AdminLoginDto;
import org.lw.server.pojo.Admin;
import org.lw.server.service.IAdminService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录控制器
 *
 * @author looveh
 * @since 2022/1/22 14:27
 **/
@RestController
@Api(value = "loginController")
public class LoginController {

    @Resource
    private IAdminService adminService;

    @ApiOperation(value = "登录返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginDto dto, HttpServletRequest request) {
        return adminService.login(dto.getUsername(), dto.getPassword(), dto.getCode(), request);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")
    public RespBean getAdminInfo(Principal principal) {
        if (null == principal) {
            return RespBean.error("找不到当前用户");
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUsername(username);
        admin.setPassword(null);
        return RespBean.success("成功", admin);

    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功!");
    }
}
